package com.spring.api.web.controller;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.PartETag;
import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.spera.aliyunContent.AliyunContent;
import com.spera.aliyunUtil.CreateOSSClient;
import com.spera.aliyunUtil.SperaOSSUtil;
import com.spera.aliyunUtil.SperaPartETag;
import com.spera.genutil.MatrixToImageWriter;
import com.spera.genutil.MemberCardZxing;
import com.spera.genutil.PasswordEncoder;
import com.spera.genutil.SpUtil;
import com.spera.genutil.TokenUtil;
import com.spera.shopoa.util.ShopOaSessionUtil.OaUser;
import com.spring.api.web.model.ApiUser;
import com.spring.api.web.model.Enregister;
import com.spring.api.web.service.ApiService;
import com.spring.common.web.service.CommonService;
import com.spring.iosservice.web.model.CourseMtsInfo;
import com.spring.iosservice.web.model.OssPartInfo;
import com.spring.iosservice.web.service.IPadApiService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.util.MD5Util;
import com.spring.security.core.util.UDate;
import com.spring.security.filestream.config.Configurations;
import com.spring.security.web.controller.BaseController;
import com.spring.security.web.dao.JedisCache;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.ValidatorResultHandler;
import com.sso.api.web.dao.SsoMapper;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

@Controller
//@RestController
@RequestMapping(value = "/api")
public class ApiController extends BaseController{
	
	@Resource private SsoMapper ssoMapper;
	@Resource private JedisCache jedisCache;
	@Resource private IPadApiService iPadApiService;
	@Resource private ApiService apiService;
	
	@Resource
	private CommonService commonService;
	
	@Resource
	private MongoTemplate mongoService;
	
	
	@ResponseBody
    @RequestMapping(value="/userCooTask/{userId}", method = RequestMethod.GET)
    @ApiOperation(value = "根据用户编号获取用户未完成的协同任务", httpMethod = "GET", response = Object.class, 
    notes = "根据用户编号获取用户未完成的协同任务",produces = "application/json; charset=utf-8")
    public Object userCooTask(@ApiParam(required = true, name = "userId", value = "用户编号") @PathVariable String userId,
    		HttpServletRequest req,HttpServletResponse resp) throws Exception{
        BaseResult ret = apiService.selectCooTaskDailyByUser(userId);
        return buildResultInfo(ret);
    }
	
	@ResponseBody
    @RequestMapping(value="/justtest", method = RequestMethod.GET)
    public Object justtest() throws Exception{
        ApiUser u = new ApiUser();
//        SxUtil s = new SxUtil();
//        s.queryDcInfo();
        return buildSuccessResultInfo(u,"");
    }
	
	@ResponseBody
    @RequestMapping(value="/name/{name}", method = RequestMethod.GET)
    @ApiOperation(value = "根据用户名获取用户对象", httpMethod = "GET", response = Object.class, notes = "根据用户名获取用户对象",produces = "application/json; charset=utf-8")
    public Object name(@ApiParam(required = true, name = "name", value = "用户名") @PathVariable String name,
    		HttpServletRequest req,HttpServletResponse resp) throws Exception{
        ApiUser u = new ApiUser();
    	u.setName(name);
    	u.setSex("1");
        return buildSuccessResultInfo(u,"");
    }
    
	@ResponseBody
    @RequestMapping(value="/desc", method = RequestMethod.POST)
    @ApiOperation(value = "根据用户名获取用户对象", httpMethod = "POST", response = Object.class, notes = "根据用户名获取用户对象",produces = "application/json; charset=utf-8")
    public Object desc(@ApiParam(required = true, name = "name", value = "用户名") @RequestParam String name) throws Exception{
        ApiUser u = new ApiUser();
    	u.setName(name);
    	u.setSex("1");
        return buildSuccessResultInfo(u,"");
    }
	
	@ResponseBody
    @RequestMapping(value="/getTest", method = RequestMethod.GET)
	@ApiOperation(value = "测试", httpMethod = "GET", response = Object.class, notes = "测试",produces = "application/json; charset=utf-8")
    public Object getTest(
    		@ApiParam(required = false, name = "aa", value = "aa") @RequestParam("aa") String aa,
    		@ApiParam(required = false, name = "bb", value = "bb") @RequestParam(value="bb",required = false) String bb,
    		HttpServletRequest request,HttpServletResponse response) throws Exception{
		System.out.println(aa+","+bb);
		Map<String,Object> m = Maps.newHashMap();
		m.put("1111", "22222");
		jedisCache.set("aa", "aaa");
		System.out.println(jedisCache.get("aa"));
        return buildSuccessResultInfo(null,"GET操作成功");
    }
	
	@ResponseBody
    @RequestMapping(value="/postTest", method = RequestMethod.POST)
    public Object postTest(@ApiParam(required = true, name = "aa", value = "aa") String aa,
    		@ApiParam(required = true, name = "bodyvalue", value = "bodyvalue") String bodyvalue) throws Exception{
		System.out.println(aa+","+bodyvalue);
        return buildSuccessResultInfo(null,"POST操作成功");
    }
    
	@ResponseBody
    @RequestMapping(value="/putTest", method = RequestMethod.PUT)
    public Object putTest() throws Exception{
        return buildSuccessResultInfo(null,"PUT操作成功");
    }
	
	@ResponseBody
    @RequestMapping(value="/deleteTest", method = RequestMethod.DELETE)
    public Object deleteTest() throws Exception{
        return buildSuccessResultInfo(null,"DELETE操作成功");
    }
    
	@RequestMapping(value="/qrcode", method = RequestMethod.GET)
    @ApiOperation(value = "根据token获取用户二维码", httpMethod = "GET", response = Object.class, notes = "二维码包含了卡内卡",produces = "application/json; charset=utf-8")
    public void Qrcode(@RequestParam(value="token") String token,String callback,HttpServletRequest request,HttpServletResponse response) throws Exception{
		 BaseResult ret = SpUtil.checkTokenNew(token, jedisCache);
		 if("1".equalsIgnoreCase(ret.getStatus())){//登录状态
			 String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			 Map<String,Object> retM = ssoMapper.getMemberCardStatus(user_id);
			 String card_number = "",member_isvaild = "";
			 if(retM!=null){//卡号及有效性
				 card_number = ApplicationUtils.Object2String(retM.get("card_number"));
				 member_isvaild = ApplicationUtils.Object2String(retM.get("member_isvaild"));
			 }
			 
			 if(card_number!=null&&"1".equalsIgnoreCase(member_isvaild)){//有效
				 String uuid = MemberCardZxing.SetSperaToken(jedisCache, card_number);
				 if(StringUtils.isNotBlank(uuid)){
			         int width = 200;  
			         int height = 200;  
			         //二维码的图片格式  
			         String format = "gif";  
			         Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
			         //内容所使用编码  
			         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
			         BitMatrix bitMatrix = new MultiFormatWriter().encode(uuid,  
			                 BarcodeFormat.QR_CODE, width, height, hints);  
			         //生成二维码  
			         ServletOutputStream sos = response.getOutputStream();
			         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
			         MatrixToImageWriter.writeToStream(bitMatrix, format, bos);  
			         byte [] buf = bos.toByteArray();  
			         sos.write(buf);  
			         bos.close();  
			         sos.close();  
				 }
			 }
		 }
    }
	
	@RequestMapping(value="/code128", method = RequestMethod.GET)
    @ApiOperation(value = "根据token获取用户条码", httpMethod = "GET", response = Object.class, notes = "条码包含了卡内卡",produces = "application/json; charset=utf-8")
    public void Code128(@RequestParam(value="token") String token,String callback,HttpServletRequest request,HttpServletResponse response) throws Exception{
		 BaseResult ret = SpUtil.checkTokenNew(token, jedisCache);
		 if("1".equalsIgnoreCase(ret.getStatus())){//登录状态
			 String user_id = jedisCache.hget(token, TokenUtil.USER_ID);
			 Map<String,Object> retM = ssoMapper.getMemberCardStatus(user_id);
			 String card_number = "",member_isvaild = "";
			 if(retM!=null){//卡号及有效性
				 card_number = ApplicationUtils.Object2String(retM.get("card_number"));
				 member_isvaild = ApplicationUtils.Object2String(retM.get("member_isvaild"));
			 }
			 
			 if(card_number!=null&&"1".equalsIgnoreCase(member_isvaild)){//有效
				 String uuid = MemberCardZxing.SetSperaToken(jedisCache, card_number);
				 if(StringUtils.isNotBlank(uuid)){
			         int width = 200;  
			         int height = 50;  
			         //二维码的图片格式  
			         String format = "gif";  
			         Hashtable<EncodeHintType, String> hints = new Hashtable<EncodeHintType, String>();  
			         //内容所使用编码  
			         hints.put(EncodeHintType.CHARACTER_SET, "utf-8");  
			         BitMatrix bitMatrix = new MultiFormatWriter().encode(uuid,  
			                    BarcodeFormat.CODE_128, width, height, hints);  
			         //生成二维码  
			         ServletOutputStream sos = response.getOutputStream();
			         ByteArrayOutputStream bos = new ByteArrayOutputStream();  
			         MatrixToImageWriter.writeToStream(bitMatrix, format, bos);  
			         byte [] buf = bos.toByteArray();  
			         sos.write(buf);  
			         bos.close();  
			         sos.close();  
				 }
			 }
		 }
    }
	
	/**
	 * 登记信息录入
	 * @param token
	 * @param enregisterIds
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
//	@OaUserPermission(value="/api/enregister")
    @RequestMapping(value="/enregister", method = RequestMethod.POST)
    @ApiOperation(value = "登记信息录入", httpMethod = "POST", response = Object.class, notes = "登记信息录入",produces = "application/json; charset=utf-8")
    public Object enregister(@RequestBody @Valid Enregister enregister,BindingResult result,HttpServletRequest req
    		){
//		OaUser oaUser = ShopOaSessionUtil.getOaUser(req);
//		if(oaUser==null){
//			return buildResultInfo(new BaseResult("0","无权限"));
//		}
		BaseResult retVal = ValidatorResultHandler.handleResult(result);
		if("0".equalsIgnoreCase(retVal.getStatus())){
			return retVal;
		}
//		BaseResult ret = SpUtil.checkTokenNew(enregister.getToken(), jedisCache);
//		if("1".equals(ret.getStatus())){//验证通过
//			String user_id = jedisCache.hget(enregister.getToken(),TokenUtil.USER_ID);
//			String username = jedisCache.hget(enregister.getToken(),TokenUtil.USER_NAME);
//			enregister.setInitialOperatorId(user_id);
//			enregister.setInitialOperatorName(username);
			//信息录入
		BaseResult ret = iPadApiService.enregister(enregister);
//		}
        return buildResultObject(ret);
    }
	
	
	/**
	 * 更新指纹
	 * @param c_user_id
	 * @param fingerHash
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
//	@OaUserPermission(value="/api/fingerHash")
    @RequestMapping(value="/fingerHash", method = RequestMethod.POST)
//	@OaUserPermission(value="/api/fingerHash")
    @ApiOperation(value = "更新指纹", httpMethod = "POST", response = Object.class, notes = "更新指纹",produces = "application/json; charset=utf-8")
    public Object fingerHash(@ApiParam(required = true, name = "c_user_id", value = "用户id") @RequestParam String c_user_id,
    		@ApiParam(required = true, name = "fingerHash", value = "指纹hash") @RequestParam String fingerHash,String enregisterId,
    		HttpServletRequest req,HttpServletResponse resp) throws Exception{
//		OaUser oaUser = ShopOaSessionUtil.getOaUser(req);
//		if(oaUser==null){
//			return buildResultInfo(new BaseResult("0","无权限"));
//		}
		BaseResult ret = new BaseResult();
		int isSuccess = iPadApiService.fingerHash(c_user_id,fingerHash,enregisterId);
		if(isSuccess==0){
			ret.setStatus("0").setMsg("操作失败");
		}
        return buildResultInfo(ret);
    }
	
	/**
	 * 更新照片头像
	 * @param c_user_id
	 * @param photoSrc
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
//	@OaUserPermission(value="/api/photoSrc")
    @RequestMapping(value="/photoSrc", method = RequestMethod.POST)
//	@OaUserPermission(value="/api/photoSrc")
    @ApiOperation(value = "更新照片头像", httpMethod = "POST", response = Object.class, notes = "更新照片头像",produces = "application/json; charset=utf-8")
    public Object photoSrc(@ApiParam(required = true, name = "c_user_id", value = "用户id") @RequestParam String c_user_id,
    		@ApiParam(required = true, name = "photoSrc", value = "头像地址") @RequestParam String photoSrc,
    		HttpServletRequest req,HttpServletResponse resp) throws Exception{
//		OaUser oaUser = ShopOaSessionUtil.getOaUser(req);
//		if(oaUser==null){
//			return buildResultInfo(new BaseResult("0","无权限"));
//		}
		BaseResult ret = new BaseResult();
		int isSuccess = iPadApiService.photoSrc(c_user_id,photoSrc);
		if(isSuccess==0){
			ret.setStatus("0").setMsg("操作失败");
		}
        return buildResultInfo(ret);
    }
	
	
	/**
	 * 获取当天指纹库
	 * @param req
	 * @param resp
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
//	@OaRestPermission(value="/api/enregisterFingers")
    @RequestMapping(value="/enregisterFingers", method = RequestMethod.GET)
//	@OaUserPermission(value="/api/enregisterFingers")
    @ApiOperation(value = "获取当天指纹库", httpMethod = "GET", response = Object.class, notes = "获取当天指纹库",produces = "application/json; charset=utf-8")
    public Object enregisterFingers(HttpServletRequest req,HttpServletResponse resp) throws Exception{
//		OaUser oaUser = ShopOaSessionUtil.getOaUser(req);
//		if(oaUser==null){
//			return buildResultInfo(new BaseResult("0","无权限"));
//		}
		BaseResult ret = iPadApiService.enregisterFingers();
        return buildResultInfo(ret);
    }
	
	
	@ResponseBody
//	@OaUserPermission(value="/api/confirmEnregister")
    @RequestMapping(value="/confirmEnregister", method = RequestMethod.POST)
//	@OaUserPermission(value="/api/enregisterFingers")
    @ApiOperation(value = "指纹密码图片等确认", httpMethod = "POST", response = Object.class, notes = "指纹(zw)密码(mm)图片(tp)等确认",produces = "application/json; charset=utf-8")
    public Object confirmEnregister(@ApiParam(required = true, name = "enregisterId", value = "登记记录编号") @RequestParam String enregisterId,
    		@ApiParam(required = true, name = "confirmType", value = "确认类型指纹(zw)密码(mm)图片(tp)") @RequestParam String confirmType,
    		HttpServletRequest req,HttpServletResponse resp) throws Exception{
//		OaUser oaUser = ShopOaSessionUtil.getOaUser(req);
		OaUser oaUser = new OaUser();
//		if(oaUser==null){
//			return buildResultInfo(new BaseResult("0","无权限"));
//		}
		boolean state = true;
		for(String type:confirmType.split(",")){
			if(!"zw".equals(type)&&!"mm".equals(type)&&!"tp".equals(type)){
				state = false;
			}
		}
		if(!state){
			BaseResult ret = new BaseResult("0","确认状态有误");
			return ret;
		}
		//是否要先判断已经入场？
		BaseResult ret = iPadApiService.confirmEnregister(enregisterId,confirmType,oaUser.getOa_user_id(),oaUser.getOa_user_name());
        return buildResultInfo(ret);
    }
	
	
	@ResponseBody
//	@OaRestPermission(value="/api/pwdValidate")
    @RequestMapping(value="/pwdValidate", method = RequestMethod.POST)
//	@OaUserPermission(value="/api/enregisterFingers")
    @ApiOperation(value = "密码验证（目前使用手机号验证）", httpMethod = "POST", response = Object.class, notes = "密码验证（目前使用手机号验证）",produces = "application/json; charset=utf-8")
    public Object pwdValidate(/*@ApiParam(required = true, name = "enregisterId", value = "登记记录编号") @RequestParam String enregisterId,*/
    		/*@ApiParam(name = "pwd", value = "验证密码") String pwd,*/
    		@ApiParam(required = true, name = "phone", value = "手机号")  @RequestParam String phone,
    		HttpServletRequest req,HttpServletResponse resp) throws Exception{
//		OaUser oaUser = ShopOaSessionUtil.getOaUser(req);
//		if(oaUser==null){
//			return buildResultInfo(new BaseResult("0","无权限"));
//		}
		BaseResult ret = iPadApiService.pwdValidate(phone);
        return buildResultInfo(ret);
    }
	
	/**
	 * 判断语音是否存在
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="/getNoAudioBaby", method = RequestMethod.GET)
    @ApiOperation(value = "获取没有语音文件的孩子", httpMethod = "GET", response = Object.class, notes = "获取没有语音文件的孩子",produces = "application/json; charset=utf-8")
    public Object getNoAudioBaby() throws Exception{
		BaseResult ret = iPadApiService.getNoAudioBaby();
        return buildResultInfo(ret);
    }
	
	/**
	 * 更新用户语音
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="/updateUserVoice", method = RequestMethod.POST)
    @ApiOperation(value = "更新用户语音", httpMethod = "POST", response = Object.class, notes = "更新用户语音",produces = "application/json; charset=utf-8")
    public Object updateUserVoice(@ApiParam(required = true, name = "babyId", value = "小孩编号") @RequestParam String babyId,
    		@ApiParam(required = true, name = "babyName", value = "小孩名") @RequestParam String babyName,
    		@ApiParam(required = true, name = "mp3Url", value = "语音地址") @RequestParam String mp3Url,
    		@ApiParam(required = true, name = "langType", value = "语音类型") @RequestParam String langType,
    		HttpServletRequest req) throws Exception{
		BaseResult ret = iPadApiService.updateUserVoice(req,babyId,babyName,mp3Url,langType);
        return buildResultInfo(ret);
    }
	
	/**
	 * 语音播报接口
	 * @param token
	 * @param enregisterIds
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="/voiceTip", method = RequestMethod.GET)
    @ApiOperation(value = "语音播报接口", httpMethod = "GET", response = Object.class, notes = "语音播报接口",produces = "application/json; charset=utf-8")
    public Object voiceTip() throws Exception{
		BaseResult ret = iPadApiService.voiceTip();
        return buildResultInfo(ret);
    }
	
	/**
	 * 语音播报结束接口
	 * @param token
	 * @param enregisterIds
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="/voiceTipOver", method = RequestMethod.GET)
    @ApiOperation(value = "语音播报结束接口", httpMethod = "GET", response = Object.class, notes = "语音播报结束接口",produces = "application/json; charset=utf-8")
    public Object voiceTipOver(@ApiParam(required = true, name = "enregisterId", value = "登记记ID") @RequestParam String enregisterId) throws Exception{
		BaseResult ret = iPadApiService.voiceTipOver(enregisterId);
        return buildResultInfo(ret);
    }
	
	@ResponseBody
    @RequestMapping(value="/needRegistrationProduct", method = RequestMethod.GET)
    @ApiOperation(value = "根据订单编号查询需要签到的产品及数量", httpMethod = "GET", response = Object.class, notes = "根据订单编号查询需要签到的产品及数量",produces = "application/json; charset=utf-8")
    public Object needRegistrationProduct(@ApiParam(required = true, name = "orderId", value = "订单ID") @RequestParam String orderId,String callback) throws Exception{
		BaseResult ret = iPadApiService.needRegistrationProduct(orderId);
        return buildResultInfo(ret,callback);
    }
    
	
	// 断点上传获取token
	@RequestMapping(value = "/uploadVideoTkByOa", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "（断点续传1）根据文件名及文件总大小获取文件上传token", httpMethod = "GET", 
		response = Object.class, notes = "（断点续传1）根据文件名及文件总大小获取文件上传token",produces = "application/json; charset=utf-8")
	public Object uploadVideoTkByOa(HttpServletRequest req, HttpServletResponse resp,
			@ApiParam(required = true, name = "file_name", value = "附件名") @RequestParam String file_name, 
			@ApiParam(required = true, name = "file_size", value = "附件大小") @RequestParam String file_size) throws ServletException,
			IOException {

//				String user_id = jedisCache.lindex(token,0);
		
//		String file_token = com.spring.security.filestream.util.TokenUtil.generateToken(file_name, file_size);
		String file_token = ApplicationUtils.randomUUID();
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		jsonStr.put("file_token", file_token);
		List<Map<String, Object>> hasin = commonService.checkVideosToken(file_token);
		if (hasin!=null&&hasin.size()>0) {
			Map<String, Object> hasInFile = hasin.get(0);
			jsonStr.put("file_id", hasInFile.get("id"));
//					jsonStr.put("image_id", hasInFile.get("base_oss_fileid"));
			jsonStr.put(ApplicationUtils.STATUS, "1");
			jsonStr.put(ApplicationUtils.MSG, "附件已存在");
			return jsonStr;
		}
		
		if (!ApplicationUtils.isNotNull(file_name)) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "附件名不能为空");
			return jsonStr;
		}
		
		if (!ApplicationUtils.isNotNull(file_size)) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "未知附件大小");
			return jsonStr;
		}
		
//				boolean f = file_name.contains(".");
//				if(!f){
//					jsonStr.put(ApplicationUtils.STATUS, "0");
//					jsonStr.put(ApplicationUtils.MSG, "未知附件类型");
//					return jsonStr;
//				}
		
//				String fileType = file_name.substring(file_name.lastIndexOf(".")+1);
//				if(!"mp4".equalsIgnoreCase(fileType)){
//					jsonStr.put(ApplicationUtils.STATUS, "0");
//					jsonStr.put(ApplicationUtils.MSG, "该附件类型不支持");
//					return jsonStr;
//				}
		
	    int partCount = SperaOSSUtil.calPartCount(Long.parseLong(file_size));
        if (partCount < 1) {
        	jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "要上传文件的大小必须大于一个Part的字节数：" + AliyunContent.PART_SIZE);
			return jsonStr;
        }
		
		try {
			//第一次上传附件时，将获取到的token存入缓存(后续断点获取不需要写入缓存,只需调用uploadOssPos去获取)
			Query q = new Query(Criteria.where("id").is(file_token));
			OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
			if(ossPart==null){
				String filePath = "baseossfile_video_tmp/"+UDate.getDate()+"/"+file_token+".mp4";
				OSSClient client = CreateOSSClient.getInstance().getOSSClient();//
		    	String uploadId = SperaOSSUtil.initMultipartUpload(client, AliyunContent.inputBucket, filePath);
		    	OssPartInfo tokenObj = new OssPartInfo();
		    	tokenObj.setId(file_token);
		    	tokenObj.setFileSize(file_size);//文件大小
		    	tokenObj.setUploadId(uploadId);//上传请求id 
		    	tokenObj.setStartPos("0");//起始位置
		    	tokenObj.setStartPart("1");//起始partId
		    	tokenObj.setTotalPart(partCount+"");//附件上传任务总共分为多少片
		    	tokenObj.setFilepath(filePath);
		    	mongoService.insert(tokenObj);
			}
			
			if (Configurations.isCrossed())
				jsonStr.put("server", Configurations.getCrossServer());
			jsonStr.put(ApplicationUtils.STATUS, "1");
			jsonStr.put(ApplicationUtils.MSG, "成功");
		} catch (JSONException e) {
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "失败");
		}
		System.out.println("TokenServlet---->doGet--->json:" + jsonStr);
		return jsonStr;
	}

	// 断点上传获取pos
	@RequestMapping(value = "/uploadVideoPosByOa", method = RequestMethod.GET)
	@ResponseBody
	@ApiOperation(value = "（断点续传2）根据文件token获取本次需上传的位置", httpMethod = "GET",
		response = Object.class, notes = "（断点续传2）根据文件token获取本次需上传的位置",produces = "application/json; charset=utf-8")
	public Object uploadVideoPosByOa(HttpServletRequest req, HttpServletResponse resp,
			@ApiParam(required = true, name = "file_token", value = "通过接口1获取的附件token") @RequestParam String file_token)
			throws ServletException, IOException {
		Map<String, Object> jsonStr = new HashMap<String, Object>();
		if(ApplicationUtils.isNotNull(file_token)){
			Query q = new Query(Criteria.where("id").is(file_token));
			OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
			if(ossPart!=null){
//					if (redisCache.exists(token)) {
				jsonStr.put("start",ossPart.getStartPos());///*redisCache.lindex(token, 2)*/
				jsonStr.put(ApplicationUtils.STATUS, "1");
				jsonStr.put(ApplicationUtils.MSG, "success");
			}else{
				jsonStr.put("start", null);
				jsonStr.put(ApplicationUtils.STATUS, "0");
				jsonStr.put(ApplicationUtils.MSG, "false");
			}
		}else{
			jsonStr.put("start", null);
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "false");
		}
		System.out.println("uploadpos---->doGet--->json:" + jsonStr);
		return jsonStr;
	}

	
	
	// 断点上传
	@RequestMapping(value = "/uploadVideoByOa", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "（断点续传3）前两步成功后根据文件token及文件流片段上传（循环连续调用）", httpMethod = "POST",
		response = Object.class, notes = "（断点续传3）前两步成功后根据文件token及文件流片段上传（循环连续调用）",produces = "application/json; charset=utf-8")
	public Object uploadVideoByOa(HttpServletRequest req, HttpServletResponse resp,
			@ApiParam(required = true, name = "file_token", value = "通过接口1获取的附件token") @RequestParam String file_token,
			@RequestParam(value = "mp4file", required = true) MultipartFile mp4file)
			throws ServletException, IOException {
		
		Map<String, Object> jsonStr = new HashMap<String, Object>();

		if(!ApplicationUtils.isNotNull(file_token)){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "token不能为空");
			return jsonStr;
		}
		
		Query q = new Query(Criteria.where("id").is(file_token));
		OssPartInfo ossPart= mongoService.findOne(q, OssPartInfo.class);
		if(ossPart==null){
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, "token已失效，请确认附件是否已上传完成");
			return jsonStr;
		}

		boolean success = false;
		String this_start = AliyunContent.PART_SIZE*(Integer.parseInt(ossPart.getStartPart()/*redisCache.lindex(token, 3)*/)-1)+"";
		String next_start = "0";
		String message = "success";
		OSSClient client = CreateOSSClient.getInstance().getOSSClient();
		try {
			
			PartETag eTag = SperaOSSUtil.uploadPartByByte(mongoService/*redisCache*/,ossPart.getFilepath(), ossPart.getUploadId()/*redisCache.lindex(token, 1)*/, client,
					mp4file.getInputStream(),mp4file.getSize(),Integer.parseInt(ossPart.getStartPart()/*redisCache.lindex(token, 3)*/));
			if(eTag!=null){
				success = true;
				next_start = (Long.parseLong(this_start)+mp4file.getSize())+"";
			}
		} catch (Exception se) {
			jsonStr.put("start", null);
			jsonStr.put(ApplicationUtils.STATUS, "0");
			jsonStr.put(ApplicationUtils.MSG, message);
			
		} finally {
			//附件片段上传成功
			if(success){
				//更新redis
				mongoService.updateFirst(q, Update.update("startPos", next_start), OssPartInfo.class);
				//当前part与总part相比 // 传递完毕
				if (/*redisCache.lindex(token, 3)*/ossPart.getStartPart().equalsIgnoreCase(ossPart.getTotalPart()/*redisCache.lindex(token, 4)*/)) {
					//拼接eTag
					List<PartETag> eTags = new ArrayList<PartETag>();
					Query q_eTags = new Query(Criteria.where("token").is(ossPart.getFilepath()));
					List<SperaPartETag> SperaETags = mongoService.find(q_eTags, SperaPartETag.class);
					for(SperaPartETag se:SperaETags){
						PartETag e = new PartETag(se.getPartNumber(),se.geteTag());
						eTags.add(e);
					}
					CompleteMultipartUploadResult ret = SperaOSSUtil.completeMultipartUpload(client,AliyunContent.inputBucket,ossPart.getFilepath(),ossPart.getUploadId()/*redisCache.lindex(token, 1)*/,eTags);
					String file_id = ApplicationUtils.randomUUID();
					String image_uuid = ApplicationUtils.randomUUID();
					
					//清除redis
//							redisCache.del(token,token+"-etag");
					mongoService.remove(q_eTags, SperaPartETag.class);
					mongoService.remove(q, OssPartInfo.class);
					
					//MTS转码
					CourseMtsInfo cm = new CourseMtsInfo();
					cm.setTranscodeJobId("0");//待转码
					cm.setImgae_uuid(image_uuid);//封面id
					cm.setModelName("common");
					cm.setToken(file_token);
					cm.setEtag(ret.getETag());
					cm.setCourseVideosId(file_id);
					cm.setOssFilePath(ossPart.getFilepath());
					cm.setC_user_id("");
					mongoService.insert(cm);
					//先预插入表
					addOssFile(image_uuid);
					addOssViedoFile(file_id,image_uuid);
					jsonStr.put("file_id", file_id);
					jsonStr.put("image_id", image_uuid);
					
				}else{
					mongoService.updateFirst(q, Update.update("startPart", (Integer.parseInt(ossPart.getStartPart())+1)+""), OssPartInfo.class);
				}
				
				jsonStr.put("start", next_start);
				jsonStr.put(ApplicationUtils.STATUS, "1");
				jsonStr.put(ApplicationUtils.MSG, message);
				System.out.println("upload---->dopost--->json:" + jsonStr);
			}else{
				jsonStr.put("start", null);
				jsonStr.put(ApplicationUtils.STATUS, "0");
				jsonStr.put(ApplicationUtils.MSG, "第"+ossPart.getStartPart()/*redisCache.lindex(token, 3)*/+"部分上传失败");
			}
		}
		return jsonStr;
	}
	
	
	private void addOssViedoFile(String file_id,String image_uuid){
		Map<String,Object> im = new HashMap<String,Object>();
		im.put("id", file_id);
		im.put("image_id", image_uuid);
		commonService.addVideosFile(im);		
	}
	
	private void addOssFile(String image_uuid){
		Map<String,Object> im = new HashMap<String,Object>();
 		im.put("id", image_uuid);
 		commonService.addOssFile(im);
	}
	
	
	/**
	 * 点触短信发送
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="/sendDcSms", method = RequestMethod.POST)
    @ApiOperation(value = "点触短信发送", httpMethod = "POST", response = Object.class, notes = "点触短信发送",produces = "application/json; charset=utf-8")
    public Object sendDcSms(@RequestParam(value="phone") String phone,
    		@RequestParam(value="phone") String content,
    		@RequestParam(value="timestamp") Long timestamp,
    		@RequestParam(value="hashcode") String hashcode,
    		String callback) throws Exception{
		BaseResult ret = new BaseResult();
    	long defTime = new Date().getTime()/1000-timestamp;
    	if(defTime>3000){
    		ret.setStatus("0").setMsg("请求超时");
    	}else if(jedisCache.exists("sendPhoneToken_"+phone)){
    		ret.setStatus("0").setMsg("验证码已存在，请稍后再发");
    	}else if(!hashcode.equals(MD5Util.string2MD5(PasswordEncoder.translateMobile(phone)+timestamp+"SmsDi6aB0Sp3ra@cZA0GzO6K3y"))){
    		ret.setStatus("0").setMsg("参数有误");
    	}else{
	    	try{
	    		ret = apiService.sendDcSms(phone,content);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		ret.setStatus("0").setMsg("系统异常");
	    	}
    	}
        return buildResultInfo(ret,callback);
    }
	
	/**
	 * 营销短信发送
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
    @RequestMapping(value="/sendYxSms", method = RequestMethod.POST)
    @ApiOperation(value = "营销短信发送", httpMethod = "POST", response = Object.class, notes = "营销短信发送",produces = "application/json; charset=utf-8")
    public Object sendYxSms(@RequestParam(value="phone") String phone,
    		@RequestParam(value="content") String content,
    		@RequestParam(value="timestamp") Long timestamp,
    		@RequestParam(value="hashcode") String hashcode,
    		String callback) throws Exception{
		BaseResult ret = new BaseResult();
    	long defTime = new Date().getTime()/1000-timestamp;
    	if(defTime>3000){
    		ret.setStatus("0").setMsg("请求超时");
    	}else if(!hashcode.equals(MD5Util.string2MD5(PasswordEncoder.translateMobile(phone)+timestamp+"SmsDi6aB0Sp3ra@cZA0GzO6K3y"))){
    		ret.setStatus("0").setMsg("参数有误");
    	}else{
	    	try{
	    		ret = apiService.sendYxSms(phone,content);
	    	}catch(Exception e){
	    		e.printStackTrace();
	    		ret.setStatus("0").setMsg("系统异常");
	    	}
    	}
        return buildResultInfo(ret,callback);
    }
}
